package com.kmis.common.security;

import cn.hutool.json.JSONUtil;
import com.kmis.web.ApiResult;
import org.springframework.security.core.AuthenticationException;
import org.springframework.security.web.AuthenticationEntryPoint;
import org.springframework.stereotype.Component;

import javax.servlet.ServletException;
import javax.servlet.ServletOutputStream;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.io.IOException;

/**
 * @author moc
 * 用户请求过程中遇见认证异常时的异常处理器
 */
@Component
public class JwtAuthenticationEntryPoint implements AuthenticationEntryPoint {
    @Override
    public void commence(HttpServletRequest request, HttpServletResponse response, AuthenticationException authException) throws IOException, ServletException {
        response.setContentType("application/json;charset=UTF-8");
        ServletOutputStream outputStream =
                response.getOutputStream();
        outputStream.write(JSONUtil.toJsonStr(ApiResult.error(HttpServletResponse.SC_UNAUTHORIZED,"认证失败，请登录！")).getBytes());
        outputStream.flush();
        outputStream.close();
    }
    }
